# -- coding: utf-8 --
import sys
import io

# 设置标准输出的编码为UTF-8
if sys.stdout.encoding != "UTF-8":
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")

# DeepSeek AI对话 - 修复API请求格式
import requests
import os
import json
from dotenv import load_dotenv

print("=== DeepSeek AI对话系统（修复版） ===")


def load_environment():
    """加载环境变量"""
    load_dotenv()
    api_key = os.getenv("DEEPSEEK_API_KEY")

    if not api_key or api_key == "你的实际DeepSeek_API_Key":
        print("❌ 请在 .env 文件中设置正确的 DEEPSEEK_API_KEY")
        return None

    print(f"✅ API Key加载成功: {api_key[:10]}...")
    return api_key


def deepseek_chat_simple(message, api_key):
    """简单的DeepSeek API调用（修复格式问题）"""
    url = "https://api.deepseek.com/chat/completions"

    headers = {"Content-Type": "application/json", "Authorization": f"Bearer {api_key}"}

    # 修复：确保messages是数组格式
    payload = {
        "model": "deepseek-chat",
        "messages": [{"role": "user", "content": message}],
        "stream": False,
        "max_tokens": 1000,
        "temperature": 0.7,
    }

    try:
        print("🔄 发送请求...")
        print(f"请求数据: {json.dumps(payload, ensure_ascii=False)[:100]}...")

        response = requests.post(url, headers=headers, json=payload, timeout=30)

        print(f"状态码: {response.status_code}")

        if response.status_code == 200:
            result = response.json()
            ai_response = result["choices"][0]["message"]["content"]
            return f"✅ {ai_response}"
        else:
            error_detail = response.text
            print(f"错误详情: {error_detail}")
            return f"❌ API错误: {response.status_code}"

    except Exception as e:
        return f"❌ 请求失败: {e}"


def deepseek_chat_with_history(message, conversation_history, api_key):
    """带历史记录的DeepSeek API调用（修复格式问题）"""
    url = "https://api.deepseek.com/chat/completions"

    headers = {"Content-Type": "application/json", "Authorization": f"Bearer {api_key}"}

    # 构建消息数组 - 确保格式正确
    messages = conversation_history + [{"role": "user", "content": message}]

    payload = {
        "model": "deepseek-chat",
        "messages": messages,  # 这应该是一个数组
        "stream": False,
        "max_tokens": 1000,
        "temperature": 0.7,
    }

    try:
        print("🔄 发送请求...")
        print(f"消息历史长度: {len(messages)}")

        response = requests.post(url, headers=headers, json=payload, timeout=30)

        print(f"状态码: {response.status_code}")

        if response.status_code == 200:
            result = response.json()
            ai_response = result["choices"][0]["message"]["content"]

            # 更新对话历史
            updated_history = messages + [{"role": "assistant", "content": ai_response}]

            # 限制历史记录长度
            if len(updated_history) > 10:
                updated_history = updated_history[-10:]

            return ai_response, updated_history

        else:
            error_detail = response.text
            print(f"错误详情: {error_detail}")
            return f"❌ API错误: {response.status_code}", conversation_history

    except Exception as e:
        return f"❌ 请求失败: {e}", conversation_history


def test_basic_api(api_key):
    """基础API测试"""
    print("\n🧪 基础API测试...")

    test_messages = [
        "Hello, how are you?",
        "What is Python programming?",
        "请用中文回答：你好",
    ]

    for i, msg in enumerate(test_messages, 1):
        print(f"\n【测试 {i}】")
        print(f"我: {msg}")
        response = deepseek_chat_simple(msg, api_key)
        print(f"AI: {response}")
        print("-" * 50)


def test_with_history(api_key):
    """带历史记录的测试"""
    print("\n🚀 历史记录功能测试...")

    conversation_history = []

    test_dialogue = [
        "你好，我的名字叫小明",
        "请记住，我喜欢编程和篮球",
        "我之前告诉你我喜欢什么？",
        "基于我们之前的对话，为我推荐一个周末活动",
    ]

    for i, msg in enumerate(test_dialogue, 1):
        print(f"\n【对话 {i}】")
        print(f"我: {msg}")

        response, conversation_history = deepseek_chat_with_history(
            msg, conversation_history, api_key
        )
        print(f"AI: {response}")
        print(f"历史记录: {len(conversation_history)} 条消息")
        print("-" * 50)


def interactive_chat(api_key):
    """交互式对话"""
    print("\n💬 交互对话模式（输入'退出'结束）")

    conversation_history = []

    while True:
        user_input = input("\n我: ").strip()

        if user_input.lower() in ["退出", "exit", "quit"]:
            print("再见！👋")
            break

        if user_input:
            if user_input == "/clear":
                conversation_history = []
                print("🗑️ 历史已清空")
                continue

            response, conversation_history = deepseek_chat_with_history(
                user_input, conversation_history, api_key
            )
            print(f"AI: {response}")


# 主程序
if __name__ == "__main__":
    api_key = load_environment()

    if api_key:
        print("\n选择测试模式:")
        print("1. 基础API测试（无历史记录）")
        print("2. 历史记录功能测试")
        print("3. 交互对话")

        choice = input("请输入选择 (1/2/3): ").strip()

        if choice == "1":
            test_basic_api(api_key)
        elif choice == "2":
            test_with_history(api_key)
        else:
            interactive_chat(api_key)
    else:
        print("\n❌ 无法启动，请先配置API Key")
